#ifndef _HTTP_SERVER_HPP
#define _HTTP_SERVER_HPP

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/signal.h>
#include <unistd.h>
#include "Task.hpp"
#include "ThreadPool.hpp"
#include "TcpServer.hpp"
#include "Protocol.hpp"
#include "Log.hpp"

#define PORT 8081

class HttpServer
{
    private:
        uint16_t port;
        bool stop;
        TcpServer* svr;
        std::string request_line;
        std::string request_header;
        std::string blank;
        std::string body;

    public:
        HttpServer(uint16_t _port = PORT)
          :port(_port), stop(true), svr(nullptr)
        {}

        void InitHttpServer()
        { 
            // 忽略SIGPIP
            // 写入错误：写入时，对方关闭了管道，就会出现SIGPIPE的情况，粗糙处理直接忽略
            signal(SIGPIPE, SIG_IGN);
            svr = TcpServer::Getinstance(port);
            svr->InitServer();
        }

        void Loop()
        {
            LOG(INFO, "Loop Begin");
            int listen_sock = svr->Sock();
            while(stop)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int fd = accept(listen_sock, reinterpret_cast<struct sockaddr*>(&peer), &len);
                if(fd < 0) continue;
                LOG(INFO, "Get a new link");

                //pthread_t tid;
                //int* sock = new int(fd);
                //pthread_create(&tid, nullptr, Entrance::HandlerRequest, (void*)sock);
                //pthread_detach(tid);
                
                // 引入线程池
                Task t(fd);
                ThreadPool<Task>::Getinstance()->PushTask(t);
            }
            LOG(INFO, "Loop End");
        }
        
        ~HttpServer()
        {}
};


#endif
